#!/usr/bin/env python
# encoding: utf-8
from pywinservicemanager import WindowsServiceConfigurationManager
from pywinservicemanager.WindowsServiceConfigurationManager import ServiceExists

__author__ = '马志'

"""

by: 马志 at: 2016/9/7 16:16
@contact: hautmz@163.com
@file: win_service_manage_helper.py
"""


def query_winservice_started(service_name="PluginService"):
    """

    by: 马志 at: ${DATE} ${TIME}
    """
    serviceExists = ServiceExists(service_name)
    if not serviceExists:
        return "NOTEXIST"
    else:
        myService = WindowsServiceConfigurationManager.GetService(service_name)
        status = myService.GetServiceStatus()
        if status["CurrentState"].StringValue()=="STOPPED":
            return "STOPPED"
        else:
            return "RUNNING"

def get_winservice_path(service_name="PluginService"):
    serviceExists = ServiceExists(service_name)
    if not serviceExists:
        return ""
    else:
        myService = WindowsServiceConfigurationManager.GetService(service_name)
        path =myService.Configurations.get("BinaryPathName").replace("PluginService.exe","")
        return path.replace('\"',"")

def stop_and_start_winservice(action="start",service_name="PluginService"):
    serviceExists = ServiceExists(service_name)
    if serviceExists:
        myService = WindowsServiceConfigurationManager.GetService(service_name)
        try:
            if action=="start":
                myService.Start()
            else:
                myService.Stop()
        except Exception,e:
            print e





def start_winservice(service_name="PluginService"):
    try:
        myService = WindowsServiceConfigurationManager.GetService(service_name)
        status = myService.GetServiceStatus()
        if status["CurrentState"].StringValue()=="STOPPED":
            myService.Start()
    except Exception,e:
        print e
